package pay.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;

@Component
public class WxHttpClient {
    private final RestTemplate restTemplate;

    @Resource
    private ObjectMapper objectMapper;

    public WxHttpClient() {
        restTemplate = new RestTemplate();
    }

    public String get(String url, Map<String, String> params) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        params.forEach(builder::queryParam);
        return restTemplate.getForObject(builder.toUriString(), String.class);
    }

    public <T> T post(String url, Object request, Class<T> responseType) {
        String response = restTemplate.postForObject(url, request, String.class);
        try {
            return objectMapper.readValue(response, responseType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("解析响应失败", e);
        }
    }
}
